/**

 @Name：layuiAdmin 用户登入和注册等
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License: LPPL

 */

layui.define(['index', 'layim', 'setter'], function (exports) {
    var $ = layui.$
        , admin = layui.admin
        , element = layui.element
        , setter = layui.setter
        , router = layui.router();
    var socket;


    var layim = layui.layim;

    let socketState = false;


    function init() {
        //websocket
        if (typeof (WebSocket) == "undefined") {
            layer.confirm('您的浏览器版本过低无法正常收货', {
                title: "提示"
                , btn: []
            });
            console.log("您的浏览器不支持WebSocket");
        } else {
            //基础配置
            layim.config({
                //初始化接口
                init: {
                    url: layui.setter.apiHost + '/admin/api/order/message/info'
                    , data: {}
                    , type: 'post'
                }
                //查看群员接口
                , members: {
                    url: layui.setter.base + 'json/layim/getMembers.js'
                    , data: {}
                }

                , uploadImage: {
                    url: layui.setter.apiHost + "/api/aliy/oss/upload"
                    , type: '' //默认post
                }
                , uploadFile: false
                , isAudio: false //开启聊天工具栏音频
                , isVideo: false //开启聊天工具栏视频

                //扩展工具栏
                , tool: []

                //,brief: true //是否简约模式（若开启则不显示主面板）

                , title: '我的订单' //自定义主面板最小化时的标题
                //,right: '100px' //主面板相对浏览器右侧距离
                //,minRight: '90px' //聊天面板最小化时相对浏览器右侧距离
                , initSkin: '3.jpg' //1-5 设置初始背景
                //,skin: ['aaa.jpg'] //新增皮肤
                , isfriend: false //是否开启好友
                , isgroup: true //是否开启群组
                , min: true //是否始终最小化主面板，默认false
                //,notice: true //是否开启桌面消息提醒，默认false
                //,voice: false //声音提醒，默认开启，声音文件为：default.mp3
                , msgbox: '../layim/msgbox.html' //消息盒子页面地址，若不开启，剔除该项即可
                , find: '../layim/find.html' //发现页面地址，若不开启，剔除该项即可
                , chatLog: '../layim/chatlog.html' //聊天记录页面地址，若不开启，剔除该项即可

            });
            var socketUrl = layui.setter.apiHost + "/ws/im/message/" + layui.data(setter.tableName)[setter.request.tokenName] || '';
            socketUrl = socketUrl.replace("https", "wss").replace("http", "ws");

            function openSocket() {
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
                socket = new WebSocket(socketUrl);
                //打开事件
                let socketLoop;
                socket.onopen = function () {
                    console.log("已建立")
                    socketState = true;
                    // layim.setChatStatus('<span style="color:#dabb92;">在线</span>');
                    //心跳保持
                    socketLoop = setInterval(function () {
                        socket.send(JSON.stringify({
                            type: 'HEARTBEAT'
                        }));
                    }, 17000);
                };
                //获得消息事件
                socket.onmessage = function (msg) {
                    //发现消息进入    开始处理前端触发逻辑
                    let msgData = JSON.parse(msg.data);
                    layim.chat({
                        name: '订单号：' + msgData.orderNum
                        , type: 'group'
                        , avatar: msgData.masterPath
                        , id: msgData.orderNum + msgData.creatorType
                        , orderId: msgData.orderId
                        , senderUserType: msgData.toUserType
                        , orderNum: msgData.orderNum
                        , toUserType: msgData.creatorType
                    });
                    layim.setChatStatus(msgData.creatorType == 'user' ? '买家' : '商家');
                    let obj = {
                        username: msgData.creatorName
                        , name: '订单号：' + msgData.orderNum
                        , avatar: msgData.creatorHeadUrl
                        , content: msgData.message
                        , type: 'group'
                        , timestamp: msgData.createTimeLong
                        , id: msgData.orderNum + msgData.creatorType
                        , orderId: msgData.orderId
                        , senderUserType: msgData.toUserType
                        , toUserType: msgData.creatorType
                    }
                    layim.getMessage(obj);
                };
                //关闭事件
                socket.onclose = function () {
                    console.log("关闭事件")
                    layim.setChatStatus('<span style="color:#FF5722;">您已断开连接</span>');
                    socketState = false;
                    reconnect();
                    clearInterval(socketLoop);
                };
                //发生了错误事件
                socket.onerror = function () {
                    console.log("发生了错误事件")
                    layim.setChatStatus('<span style="color:#FF5722;">您已断开连接</span>');
                    socketState = false;
                    // reconnect();
                    clearInterval(socketLoop);
                }
            }

            function reconnect() {
                openSocket(socket)
                /*layer.confirm('聊天室网络链接已断开，是否需要重连？', {
                    title: "提示"
                    ,btn: ['是','否']
                }, function(index){
                    openSocket(socket)
                    layer.close(index);
                });*/
            }

            //监听在线状态的切换事件
            layim.on('online', function (status) {
                layer.msg(status);
            });

            //监听签名修改
            layim.on('sign', function (value) {
                layer.msg(value);
            });
            //监听layim建立就绪
            layim.on('ready', function (res) {
                openSocket(socket)
            });
            layim.on('getState', function () {
                return socketState;
            });

            //监听发送消息
            layim.on('sendMessage', function (data) {
                console.log("sendMessage："+data)
                let To = data.to;
                let mine = data.mine;
                socket.send(JSON.stringify({
                    type: 'USER_MESSAGE',
                    groupId: To.groupId,
                    messageContent: mine.content
                }));
            });
            //监听查看群员
            layim.on('members', function (data) {
                //console.log(data);
            });

            //监听聊天窗口的切换
            layim.on('chatChange', function (res) {
                var type = res.data.type;
                if (type === 'friend') {
                    //模拟标注好友状态
                    //layim.setChatStatus('<span style="color:#FF5722;">在线</span>');
                } else if (type === 'group') {
                    // //模拟系统消息
                    // layim.getMessage({
                    //   system: true
                    //   ,id: res.data.id
                    //   ,type: "group"
                    //   ,content: '模拟群员'+(Math.random()*100|0) + '加入群聊'
                    // });
                }
            });
        }
    }

    var Methods = {
        initGroup: function (admin) {
            return $.ajax({
                url: setter.apiHost + "/admin/api/order"
                , type: "POST"
                , contentType: "application/json"
                , data: JSON.stringify(admin)
            })
        }
    }
    exports('im', {
        methods: Methods,
        open: function (groupId, orderNum, masterPath, satatusEml, senderUserType, toUserType) {
            //自定义会话
            layim.chat({
                name: '订单号：' + orderNum
                , type: 'group'
                , avatar: masterPath
                , id: orderNum + toUserType
                , groupId: groupId
                , orderNum: orderNum
                , senderUserType: senderUserType
                , toUserType: toUserType
            });
            layim.setChatStatus(satatusEml);
        }
        , init: function () {
            init();
        }
    });
});
